import {ExclamationCircleOutlined, PlusOutlined} from '@ant-design/icons';
import {Button, Divider, Drawer, Input, message, Modal, Select, Tag} from 'antd';
import React, {useEffect, useRef, useState} from 'react';
import {PageContainer} from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import ProDescriptions from '@ant-design/pro-descriptions';
import ProductForm from './components/ProductForm';
import {
  addProduct,
  offSale,
  onSale,
  queryProcessFlow,
  queryProduct,
  removeProduct,
  updateProduct
} from '@/services/product';
import {queryCustomer} from '@/services/customer';

const TableList = () => {
  const [createModalVisible, handleModalVisible] = useState(false);
  const [selectedRow, handleSelectedRow] = useState({});
  const [formType, handleFormType] = useState(1); // 1.新增 2.编辑 3.详情
  const [formBaseData, setFormBaseData] = useState({
    processData: [],
    customerData: []
  })
  const actionRef = useRef();
  const [row, setRow] = useState();
  const [selectedRowsState, setSelectedRows] = useState([]);
  const {Option} = Select;
  const handleCreateModalVisible = () => {
    handleFormType(1)
    handleModalVisible(true)
  }
  const handleUpdateModalVisible = (record) => {
    handleFormType(2)
    handleSelectedRow(record)
    handleModalVisible(true)
  }
  const handleDetailModalVisible = (record) => {
    handleFormType(3)
    handleSelectedRow(record)
    handleModalVisible(true)
  }

  const getProcessFlowData = async () => {
    try {
      await queryProcessFlow({
        pageNum: 1,
        pageSize: 9999,
        hidden: 0
      }).then(res => {
        if (res && res.status === '0') {
          const data = formBaseData;
          data.processData = res.result.records;
          setFormBaseData(data)
        } else {
          message.error(res.message);
        }
      });
    } catch (error) {
      //console.log((error)
    }
  };

  const getCustomerData = async () => {
    try {
      await queryCustomer({
        pageNum: 1,
        pageSize: 9999
      }).then(res => {
        if (res && res.status === '0') {
          const data = formBaseData;
          data.customerData = res.result.records;
          setFormBaseData(data)
        } else {
          message.error(res.message);

        }
      });

    } catch (error) {
      //console.log((error)
    }
  }

  useEffect(() => {
    const success = getProcessFlowData();
    getCustomerData()
  }, [])

  const handleAdd = async (fields) => {
    const hide = message.loading('正在添加');

    try {
      await addProduct({...fields}).then(res => {
        if (res && res.status === '0') {
          hide();
          message.success('添加成功');
          handleModalVisible(false)
          if (actionRef.current) {
            actionRef.current.reload();
          }
        } else {
          message.error(res.message);
        }
      });

      return true;
    } catch (error) {
      hide();
      message.error('添加失败请重试！');
      return false;
    }
  };

  const handleUpdate = async (fields) => {
    const hide = message.loading('正在更新');

    try {
      await updateProduct({...fields}).then(res => {
        if (res && res.status === '0') {
          hide();
          message.success('更新成功');
          handleModalVisible(false)
          if (actionRef.current) {
            actionRef.current.reload();
          }
        } else {
          message.error(res.message);
        }
      });

      return true;
    } catch (error) {
      hide();
      message.error('更新失败请重试！');
      return false;
    }
  };

  const handleRemove = async (selectedRows) => {
    const hide = message.loading('正在删除');
    if (!selectedRows) return true;

    try {
      await removeProduct({
        ...selectedRows
      });
      hide();
      message.success('删除成功，即将刷新');
      if (actionRef.current) {
        actionRef.current.reload();
      }
      return true;
    } catch (error) {
      hide();
      message.error('删除失败，请重试');
      return false;
    }
  };

  const handleOnOffSale = async (selectedRows, status) => {
    try {
      status === 1 ? await onSale({...selectedRows}) : await offSale({...selectedRows});
      message.success(status === 1 ? '上架成功' : '下架成功');
      if (actionRef.current) {
        actionRef.current.reload();
      }
      return true;
    } catch (error) {
      message.error(status === 1 ? '上架失败' : '下架失败');
      return false;
    }
  };

  const onSubmit = (data) => {
    let success;
    if (formType === 1) {
      success = handleAdd(data)
    } else {
      data.productId = selectedRow.productId
      success = handleUpdate(data)
    }
  }

  const deleteConfig = (record) => {
    Modal.confirm({
      title: '注意',
      icon: <ExclamationCircleOutlined/>,
      content: `是否要删除编码为 【${record.productCode} 】的产品？`,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        const success = await handleRemove(record)
      }
    });
  };

  const columns = [
    {
      title: '序号',
      dataIndex: 'key',
      hideInForm: true,
      hideInSearch: true,
      render: (text, record, index, action) => {
        return `${index + 1}`
      }
    },
    {
      title: '产品编码',
      dataIndex: 'productCode',
      tip: '产品编码是唯一的',
      hideInForm: true,
      copyable: true,
      formItemProps: {
        rules: [
          {
            max: 32,
            message: '产品编码最大长度为32'
          },
        ],
      },
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <Input placeholder={'请输入产品编码'}/>;
      }
    },
    // {
    //   title: '产品名称',
    //   dataIndex: 'productName',
    //   renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
    //     return <Input {...fieldProps} placeholder={'请输入产品名称'}/>;
    //   }
    // },
    {
      title: '客户名称',
      dataIndex: 'custName',
      formItemProps: {
        rules: [
          {
            max: 32,
            message: '客户名称最大长度为32'
          },
        ],
      },
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <Input {...fieldProps} placeholder={'请输入客户名称'}/>;
      }
    },
    {
      title: '客户型号',
      dataIndex: 'custModelNo',
      formItemProps: {
        rules: [
          {
            max: 32,
            message: '客户型号最大长度为32'
          },
        ],
      },
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <Input {...fieldProps} placeholder={'请输入客户型号'}/>;
      }
    },
    {
      title: 'PCB层数',
      dataIndex: 'pcbLayerNum',
      hideInSearch: true
    },
    {
      title: '拼板PCB数',
      dataIndex: 'panelPcbNum',
      hideInSearch: true
    },
    {
      title: '板材类型',
      dataIndex: 'pcbType',
      hideInSearch: true
    },
    {
      title: '拼板长度（mm）',
      dataIndex: 'panelLength',
      hideInSearch: true
    },
    {
      title: '拼板宽度（mm）',
      dataIndex: 'panelWidth',
      hideInSearch: true
    },
    {
      title: '芯板内层厚度（mm）',
      dataIndex: 'boardInnerThickness',
      hideInSearch: true,
      hideInTable: true
    },
    {
      title: '备注',
      dataIndex: 'remark',
      hideInSearch: true,
      hideInTable: true,
      valueType: 'textarea'
    },
    {
      title: '产品转化进度',
      dataIndex: 'productConvertProgress',
      hideInSearch: true,
      hideInForm: true,
      render: (text, record, index) => {
        if (text && text !== '-') {
          return (
            <Tag>{text === 0 ? '草稿' :
              text === 1 ? '待审批' :
                text === 2 ? '工程评审中' :
                  text === 3 ? '生产评审中' :
                    text === 4 ? '工程资料中' :
                      text === 5 ? '转化完成' :
                        text}</Tag>
          )
        } else {
          return text
        }
      }
    },
    {
      title: '状态',
      dataIndex: 'productStatus',
      sorter: true,
      hideInSearch: true,
      hideInForm: true,
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <Select>
          <Option value={-1}>草稿</Option>
          <Option value={0}>草稿</Option>
          <Option value={1}>已上架</Option>
          <Option value={2}>已下架</Option>
          <Option value={3}>初始化</Option>
        </Select>;
      },
      render: (text, record, index) => {
        return (
          <Tag color={text === 0 ? 'magenta' :
            text === 1 ? 'green' :
              text === 2 ? 'red' :
                'gold'
          }>{text === 0 ? '草稿' :
            text === 1 ? '已上架' :
              text === 2 ? '已下架' :
                '初始化'}</Tag>
        )
      }
    },
    {
      title: '创建人',
      dataIndex: 'createBy',
      hideInSearch: true,
      hideInForm: true
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      sorter: true,
      valueType: 'dateTime',
      hideInSearch: true,
      hideInForm: true
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a onClick={() => handleDetailModalVisible(record)}>
          详情
        </a>,
        <Divider type="vertical" style={{display: record.productStatus === 0 ? 'block' : 'none'}}/>,
        <a style={{display: record.productStatus === 0 ? 'block' : 'none'}}
           onClick={() => handleUpdateModalVisible(record)}>修改</a>,
        <Divider type="vertical"
                 style={{display: record.productStatus === 0 || record.productStatus === 3 ? 'none' : ''}}/>,
        <a style={{display: record.productStatus === 0 || record.productStatus === 3 ? 'none' : ''}}
           onClick={() => handleOnOffSale(record, record.productStatus === 1 ? 2 : 1)}>{record.productStatus === 1 ? '下架' : '上架'}</a>,
        <Divider style={{display: record.productStatus === 0 ? 'block' : 'none'}} type="vertical"/>,
        <a style={{display: record.productStatus === 0 ? 'block' : 'none'}} onClick={() => deleteConfig(record)}>删除</a>,
      ],
    },
  ];

  return (
    <PageContainer content={createModalVisible ? '新增产品：创建一款适合的新产品' : ''}>
      <ProTable style={{display: createModalVisible ? 'none' : 'block'}}
                actionRef={actionRef}
                rowKey="productCode"
                search={{
                  labelWidth: 120,
                }}
                toolBarRender={() => [
                  <Button type="primary" onClick={() => handleCreateModalVisible()}>
                    <PlusOutlined/> 新建
                  </Button>,
                ]}
                request={async (params, sorter, filter) => {
                  const param = {...params, pageNum: params.current};
                  if (param.materialStatus === -1) {
                    param.materialStatus = null;
                  }
                  const res = await queryProduct(param)
                  return {
                    data: res.result.records,
                    success: true,
                    total: res.result.total
                  }
                }}
                columns={columns}
      />
      {
        createModalVisible ? <ProductForm onCancel={() => handleModalVisible(false)}
                                          visible={createModalVisible}
                                          onSubmit={(v) => onSubmit(v)}
                                          formType={formType}
                                          dataDetail={selectedRow}
                                          baseData={formBaseData}></ProductForm> : <></>
      }


      <Drawer
        width={600}
        visible={!!row}
        onClose={() => {
          setRow(undefined);
        }}
        closable={false}
      >
        {row?.productCode && (
          <ProDescriptions
            column={2}
            title={row?.productCode}
            request={async () => ({
              data: row || {},
            })}
            params={{
              id: row?.productCode,
            }}
            columns={columns}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default TableList;
